package com.adams.app.ui.adapter;

import com.adams.app.R;
import com.adams.app.data.RequestManager;
import com.adams.app.model.Food;
import com.adams.app.vendor.HappyGyApi;
import com.android.volley.toolbox.ImageLoader;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class FoodsAdapter extends CursorAdapter {

	private LayoutInflater mLayoutInflater;
	private ListView mListView;
	private Drawable mDefaultImageDrawable = new ColorDrawable(Color.argb(255,
			201, 201, 201));
	
	public FoodsAdapter(Context context, ListView listView) {
		super(context, null, false);
		mLayoutInflater = LayoutInflater.from(context);
		mListView = listView;
	}

	@Override
	public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
		return mLayoutInflater.inflate(R.layout.past_food_item, null);
	}
	
	@Override
	public Food getItem(int position) {
		mCursor.moveToPosition(position);
		return Food.fromCursor(mCursor);
	}

	
	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		Holder holder = getHolder(view);
		if (holder.imageRequest != null) {
			holder.imageRequest.cancelRequest();
		}

		view.setEnabled(!mListView.isItemChecked(cursor.getPosition()
				+ mListView.getHeaderViewsCount()));

		Food food = Food.fromCursor(cursor);
		
		RequestManager.loadImage(HappyGyApi.BASE_URL
				+ food.picture, RequestManager.getImageListener(
				holder.image, mDefaultImageDrawable, mDefaultImageDrawable));
		
		holder.name.setText(food.name);
		if (food.tel == null || "".equals(food.tel.trim())) {
			holder.phone.setText("联系电话：暂无");
		} else {
			holder.phone.setText("联系电话:"+food.tel);
		}
		
		if (food.address == null || "".equals(food.address.trim())) {
			holder.address.setText("地址:暂无");
		} else {
			holder.address.setText("地址:"+food.address);
		}
	}
	
	
	private Holder getHolder(final View view) {
		Holder holder = (Holder) view.getTag();
		if (holder == null) {
			holder = new Holder(view);
			view.setTag(holder);
		}
		return holder;
	}

	private class Holder {
		public ImageView image;
		public TextView name;
		public TextView phone;
		public TextView address;
		public ImageLoader.ImageContainer imageRequest;

		public Holder(View view) {
			image = (ImageView) view.findViewById(R.id.foods_image);
			name = (TextView) view.findViewById(R.id.foods_name);
			phone = (TextView) view.findViewById(R.id.food_phone);
			address = (TextView) view.findViewById(R.id.food_address);
		}
	}

}
